import datetime
import requests
import json
import asyncio
import subprocess
from urllib.parse import urljoin

class HttpClientToChe:
    baseurl="https://openapi.sophnet.com/bjriscv/server2/"
    #baseurl="http://192.168.31.38:3060/"
# 生成音频
    def generate_voice(self,content):
        url = self.baseurl+"v1/generate_voice"
        payload = json.dumps({"content": content})
        headers = {
            'Content-Type': 'application/json'
        }
        timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        response = requests.request("POST", url, headers=headers, data=payload)
        path=timestamp +'output.mp3'
        if response.status_code == 200:
                # 保存响应内容到文件
            with open(path, 'wb') as file:
                file.write(response._content)
                # 使用 subprocess 播放音频文件
        else:
            print(f"Error: {response.status_code} - {response.text}")
        return path

    def get_chat_completion(self,messages):
        default_model="qwen1_5-0_5b-chat-q5_k_m.gguf" 
        default_frequency_penalty=1.5
        default_presence_penalty=1 
        default_temperature=0.8
        default_max_tokens=512
        default_top_k=10
       # url = "https://openapi.sophnet.com/bjriscv/v1/chat/completions"
        url = self.baseurl+"v1/chat/completions"
        payload = json.dumps({
            "model": default_model,  # 使用默认模型，除非提供了特定的模型
            "frequency_penalty": default_frequency_penalty,
            "presence_penalty": default_presence_penalty,
            "temperature": default_temperature,
            "max_tokens": default_max_tokens,
            "top_k": default_top_k,
            "messages": messages
        })
        
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'  # 替换为您的API密钥
        }
                
    # 调用函数
        try:
            response = requests.post(url, headers=headers, data=payload)
            response.raise_for_status()  # 检查请求是否成功
            responsecontet=response.json()
            #return response.json()
            # 提取choices数组中的第一个元素（通常情况下只有一个）
            first_choice = responsecontet.get('choices', [{}])[0]
            # 提取message对象中的content
            content = first_choice.get('message', {}).get('content', 'No content found')
            print(content)
            return content
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
            return None

    def get_bigdl_chat_completion(self,text):      
        url = self.baseurl+"v1/chat/completions"
        payload = json.dumps({
            "text": text,  # 使用默认模型，除非提供了特定的模型
          
        })
        
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'  # 替换为您的API密钥
        }
                
    # 调用函数
        try:
            response = requests.post(url, headers=headers, data=payload)
            response.raise_for_status()  # 检查请求是否成功
            responsecontet=response.json()
            #return response.json()
            # 提取choices数组中的第一个元素（通常情况下只有一个）
            content = responsecontet.get('content')
            print(content)
            return content
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
            return None

    def post_audio_transcription(self,audio_file_path):
        url = self.baseurl+"v1/audio/transcriptions"
       # url = "https://openapi.sophnet.com/bjriscv/v1/audio/transcriptions"
        # 替换 'YOUR_API_KEY' 为您的实际API密钥
        headers = {
            
            'Authorization': 'Bearer no-key'
        }
    
        try:
            response =  requests.request("POST", url, headers=headers,  files={'audio_file': ('dataaudio.wav', open(audio_file_path, "rb")) })
            print(response)
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
            return None

#生成bigdl问问题
    def create_bigdl_chat_question(self,text):      
        url = self.baseurl+"v1/chat/create_quesion"
        payload = json.dumps({
            "text": text,  # 使用默认模型，除非提供了特定的模型
          
        })
        
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'  # 替换为您的API密钥
        }
                
    # 调用函数
        try:
            response = requests.post(url, headers=headers, data=payload)
            response.raise_for_status()  # 检查请求是否成功
            responsecontet=response.json()
            #return response.json()
            # 提取choices数组中的第一个元素（通常情况下只有一个）
            content = responsecontet.get('content')
            print(content)
            return content
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
            return None
    #获取所有问题
    def get_mianshi_allquestion(self):      
        url = self.baseurl+"/v1/chat/get_all_quesions"
      
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'  # 替换为您的API密钥
        }
                
    # 调用函数
        try:
            response = requests.post(url, headers=headers)
            response.raise_for_status()  # 检查请求是否成功
            responsecontet=response.json()
            #return response.json()
            # 提取choices数组中的第一个元素（通常情况下只有一个）
            quesiton_array = responsecontet.get('quesiton_array')
            return quesiton_array
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
            return None
    #获取index的问题
    def get_index_question(self,index):
        url = self.baseurl+"v1/chat/get_quesion_of_index"
        payload = json.dumps({
            "index": index,  # 使用默认模型，除非提供了特定的模型
          
        })
        
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'  # 替换为您的API密钥
        }
                
    # 调用函数
        try:
            response = requests.post(url, headers=headers, data=payload)
            response.raise_for_status()  # 检查请求是否成功
            responsecontet=response.json()
            #return response.json()
            # 提取choices数组中的第一个元素（通常情况下只有一个）
            content = responsecontet.get('content')
            print(content)
            return content
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
            return None
        pass
    
    def get_bigdl_fenshu(self,text,index):      
        url = self.baseurl+"v1/chat/get_fenshu"
        payload = json.dumps({
            "text": text,  # 使用默认模型，除非提供了特定的模型
            "index":index
        })
        
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'  # 替换为您的API密钥
        }
                
    # 调用函数
        try:
            response =requests.post(url, headers=headers, data=payload)
            response.raise_for_status()  # 检查请求是否成功
            responsecontet=response.json()
            #return response.json()
            # 提取choices数组中的第一个元素（通常情况下只有一个）
            content = responsecontet.get('content')
            print(content)
            return content
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
            return None



    def get_all_pingjia():
        pass
    
# 使用函数的例子：
messages = [
    {"role": "system", "content": "you are helpful assistant."},
    {"role": "user", "content": "今天的天气怎么样"}
]
#response = get_chat_completion(messages)

 # 确保您的文件路径和文件名是正确的
#files=[
#  ('audio_file',('audio.mp3',open('E://whispertest/audio.mp3','rb'),'audio/mp3'))
#]
#files={'audio_file',open(,'rb')}

#result = post_audio_transcription('dataaudio.wav')
#print(result)       

# async def main():
    # content = "Hello, world!"
    # await generate_voice(content)
# 运行事件循环
# asyncio.run(main())